package com.example.demo.client;

import feign.RequestInterceptor;
import io.github.jhipster.security.uaa.LoadBalancedResourceDetails;
import org.springframework.cloud.security.oauth2.client.feign.OAuth2FeignRequestInterceptor;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.security.oauth2.client.DefaultOAuth2ClientContext;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @Desc
 * @Author zhengmf
 * @Date 2020-02-16 17:50:56
 */
@Component
public class AuthorizedClientHttpRequestInterceptor implements ClientHttpRequestInterceptor {

    private final LoadBalancedResourceDetails loadBalancedResourceDetails;

    public AuthorizedClientHttpRequestInterceptor(LoadBalancedResourceDetails loadBalancedResourceDetails) {
        this.loadBalancedResourceDetails = loadBalancedResourceDetails;
    }

    @Override
    public ClientHttpResponse intercept(HttpRequest httpRequest, byte[] bytes, ClientHttpRequestExecution clientHttpRequestExecution) throws IOException {
        RequestInterceptor requestInterceptor = new OAuth2FeignRequestInterceptor(new DefaultOAuth2ClientContext(), loadBalancedResourceDetails);
        String token = ((OAuth2FeignRequestInterceptor) requestInterceptor).getToken().getValue();
        HttpHeaders headers = httpRequest.getHeaders();
        headers.add(OAuth2FeignRequestInterceptor.AUTHORIZATION,String.format("%s %s", OAuth2FeignRequestInterceptor.BEARER, token));
        return clientHttpRequestExecution.execute(httpRequest, bytes);
    }
}
